/*
 * Copyright (c) 2025 Li Auto Inc. and its affiliates
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <lihal_ipcf_interface.h>

#include <transport/ReceiverResource.h>
#include "IPCTransport.h"
#include "IPCChannelResource.h"

namespace vbs {
namespace transport {

IPCChannelResource::IPCChannelResource(IPCTransport* transport, uint32_t maxMsgSize,
                                       std::shared_ptr<ReceiverResource> receiver)
    : ChannelResource(maxMsgSize), message_receiver_(receiver), transport_(transport) {

    thread(std::thread(&IPCChannelResource::perform_listen_operation, this));
}

IPCChannelResource::~IPCChannelResource() {
    message_receiver_ = nullptr;
    transport_ = nullptr;
}

void IPCChannelResource::perform_listen_operation() {
    Locator locator;
    LOCATOR_INVALID(locator);
    logInfo(RTPS_MSG_OUT, "IPCChannelResource  start listening  ... ");

    while (alive()) {
        // Blocking receive.
        unsigned char* buffer = message_buffer();
        uint32_t length = 0;

        length = lihal_ipcf_vbs_recv(buffer, buffer_size(), -1);
        if (length <= 0) {
            continue;
        }

        // Processes the data through the CDR Message interface.
        if (message_receiver() != nullptr) {
            message_receiver()->OnDataReceived(buffer, length, locator, locator);
        } else if (alive()) {
            logWarning(RTPS_MSG_IN, "Received Message, but no receiver attached");
        }
    }

    logError(RTPS_MSG_OUT, "IPCChannelResource  exit  perform_listen_operation.");

    message_receiver(nullptr);
}

}  // namespace transport
}  // namespace vbs
